package aModelLayer;

import java.util.Random;

public class Battle {
	public BattleCharacter[] battleCharacters;
	public BattleEnemy[] battleEnemies;
	
	public boolean hasWon;
	public boolean hasLost;
	
	public Battle(Game model) {
		battleCharacters = model.getBattleCharacters();
		
		Random generator = new Random();
		int numOfEnemies = generator.nextInt(3) + 1;
		
		battleEnemies = new BattleEnemy[numOfEnemies];
		for (int i = 0; i < battleEnemies.length; i++) 
			battleEnemies[i] = new BattleEnemy(0);
		
		hasWon = false;
		hasLost = false;
	}
	
	public void characterAttack(int source, int target) {
		int attackStrength = battleCharacters[source].getStrength();
		int targetHealth = battleEnemies[target].getCurrentHealth();
		
		if (targetHealth - attackStrength <= 0) {
			battleEnemies[target].setCurrentHealth(0);
		} else {
			battleEnemies[target].setCurrentHealth(targetHealth - attackStrength);
		}
		
		if (battleWon()) {
			hasWon = true;
		}		
	} 
	
	public void enemyAttack(int source, int target) {
		int attackStrength = battleEnemies[source].getStrength();
		int targetHealth = battleCharacters[target].getCurrentHealth();
		
		if (targetHealth - attackStrength <= 0) {
			battleCharacters[target].setCurrentHealth(0);
		} else {
			battleCharacters[target].setCurrentHealth(targetHealth - attackStrength);
		}
		
		if (battleLost()) {
			hasLost = true;
		}	
	}
	
	public boolean battleLost() {
		boolean stillAlive = false;
		for (int i = 0; i < battleCharacters.length; i++) {
			if (battleCharacters[i].getCurrentHealth() > 0) {
				stillAlive = true;
			}
		}
		
		return !stillAlive;
	}
	
	public boolean battleWon() {
		boolean stillAlive = false;
		for (int i = 0; i < battleEnemies.length; i++) {
			if (battleEnemies[i].getCurrentHealth() > 0)
				stillAlive = true;
		}
		
		return !stillAlive;
	}

	public BattleEnemy[] getBattleEnemies() {
		return battleEnemies;
	}
	
}
